#!/bin/bash

#set -e # compileall can fail the installation 

echo "Starting postinstall"
echo "Thonny was installed to $2"

PYVER="3.10"
PYFWK="$2/Thonny.app/Contents/Frameworks/Python.framework"
PYBIN="$PYFWK/Versions/$PYVER/bin"
PYINT="$PYBIN/python$PYVER"
PYLIB="$PYFWK/Versions/$PYVER/lib/python$PYVER"
PYAPP="$PYFWK/Versions/$PYVER/Resources/Python.app/Contents/MacOS/Python"

echo "Setting launcher shebang"
sed -i '' "s:SHEBANG_PY:$PYAPP -I:g" "$2/Thonny.app/Contents/MacOS/thonny"


echo "Compiling standard library"

"$PYINT" -E -s -Wi \
    "$PYLIB/compileall.py" -q -j0 -f \
    -x 'bad_coding|badsyntax|site-packages|lib2to3/tests/data' \
    "$PYLIB"

"$PYINT" -E -s -Wi \
    "$PYLIB/compileall.py" -q -j0 -f \
    -x badsyntax \
    "$PYLIB/site-packages"


echo "Tweaking cffi"
if [[ $(uname -m) == 'arm64' ]]
then
  mv $PYLIB/site-packages/_cffi_backend.cpython-310-darwin-arm46.so $PYLIB/site-packages/_cffi_backend.cpython-310-darwin.so
else
  rm $PYLIB/site-packages/_cffi_backend.cpython-310-darwin-arm46.so
fi


echo "Done postinstall!"

exit 0
